import axios from 'axios'
import QS from 'qs'

// 环境的切换
if (process.env.NODE_ENV == 'development') {
    axios.defaults.baseURL = 'http://api.juan9.com'
} else if (process.env.NODE_ENV == 'production') {
    axios.defaults.baseURL = 'http://api.juan9.com'
}

// 请求超时时间
axios.defaults.timeout = 15000

// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

// 响应拦截器
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response)
        } else {
            return Promise.reject(response)
        }
    },
    // 服务器状态码不是200的情况
    error => {
        if (error.response.status) {
        }
        return Promise.reject(error.response)
    }
)

export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url,
            {
                params: params
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                if (!err.response) {
                } else {
                    reject(err.data)
                }
            })
    })
}

export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                if (!err.response) {
                } else {
                    reject(err.data)
                }
            })
    })
}

export function deletes(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, {
            data: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

export default axios
